<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript">
    /*******************第一种*/
    function init(){
        var name='Mozilla111';// name 是一个被 init 创建的局部变量
        function displayName(){ //displayName()是内部函数，一个闭包
            alert(name);//使用了父函数中声明的变量
        }
        displayName();//函数内部自己调用
    }
    init()
    /*******************第二种*/
    function makeFunc() {
        var name = "Mozilla222";
        function displayName() {
            alert(name);
        }
        return displayName;//内部函数 displayName() 在执行前，被外部函数返回
    }

    var myFunc = makeFunc(); //内部函数被外部函数返回，调用外部函数的时候就需要定义一个变量
    myFunc();
    /*******************第三种*/
    function makeAdder(x){
        return function(y){
            return x+y;
        }
    }
    var add5=makeAdder(5);
    var add10=makeAdder(10);
    alert(add5(2)); //7
    alert(add10(2)); //7
    /*******************第四种*/
    var Counter=(function(){
        var privateCounter = 0;
        function changeBy(val){
            privateCounter+=val;
        }
        return {
            increment: function() {
                changeBy(1);
            },
            decrement: function() {
                changeBy(-1);
            },
            value: function() {
                return privateCounter;
            }
        }
    })();
    console.log(Counter.value()); /* logs 0 */
    Counter.increment();
    Counter.increment();
    console.log(Counter.value()); /* logs 2 */
    Counter.decrement();
    console.log(Counter.value()); /* logs 1 */
    /*******************第五种*/
    var makeCounter = function() {
        var privateCounter = 0;
        function changeBy(val) {
            privateCounter += val;
        }
        return {
            increment: function() {
                changeBy(1);
            },
            decrement: function() {
                changeBy(-1);
            },
            value: function() {
                return privateCounter;
            }
        }
    };
    var Counter1 = makeCounter();
    var Counter2 = makeCounter();
    console.log(Counter1.value()); /* logs 0 */
    Counter1.increment();
    Counter1.increment();
    console.log(Counter1.value()); /* logs 2 */
    Counter1.decrement();
    console.log(Counter1.value()); /* logs 1 */
    console.log(Counter2.value()); /* logs 0 */
</script>
</body>
</html>